<template>
    <div class="channel">
        <div class="header" v-show="showHeader">
            <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
                <el-form-item label="渠道名称">
                    <el-input v-model="queryInfo.channelName" placeholder="请输入渠道名称" clearable @clear="getUserList()" />
                </el-form-item>
                <el-form-item label="渠道状态">
                    <el-select v-model="queryInfo.type" clearable placeholder="请选择渠道状态">
                        <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="渠道类型">
                    <el-select v-model="queryInfo.status" clearable placeholder="请选择渠道类型">
                        <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker v-model="queryInfo.createTime" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" range-separator="-" format="YYYY-MM-DD HH:mm:ss"
                        date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="findChannelList"> <el-icon>
                            <Search />
                        </el-icon>搜索</el-button>
                    <el-button class="addBtn" @click="resetForm"> <el-icon>
                            <Refresh />
                        </el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="nav">
            <div class="l">
                <el-button type="primary" plain @click="openUserDialog"><el-icon>
                        <Plus />
                    </el-icon>新增</el-button>
                <el-button v-if="selectedActivities.length == 0 || selectedActivities.length > 1" disabled type="success" plain><el-icon><Edit /></el-icon>修改</el-button>
                <el-button v-else type="success" plain @click="openNewDialog"><el-icon><Edit /></el-icon>修改</el-button>
                <el-button v-if="selectedActivities.length == 0" disabled type="danger" plain
                    @click="deleteActivityAll"><el-icon>
                        <Delete />
                    </el-icon>删除</el-button>
                <el-button v-else type="danger" plain @click="deleteActivityAll"><el-icon>
                        <Delete />
                    </el-icon>删除</el-button>
                <el-button type="info" plain @click="openDialog1()"><el-icon>
                        <Upload />
                    </el-icon>导入</el-button>
                <el-button type="warning" plain @click="exportToExcel"><el-icon>
                        <Download />
                    </el-icon>导出</el-button>
            </div>
            <div class="r">
                <el-button :icon="Search" circle @click="showHeader = !showHeader" />
                <el-button :icon="Refresh" circle @click="setPage(1)" />
            </div>
        </div>
        <div class="toBe">
            <el-table :data="channel" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="channelId" label="渠道编号" />
                <el-table-column prop="channelName" label="渠道名称" />
                <el-table-column label="渠道类型">
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.type == 1">线上渠道</el-tag>
                        <el-tag type="primary" v-if="scope.row.type == 2">线下渠道</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="updateBy" label="创建人" />
                <el-table-column label="渠道状态">
                    <template #default="scope">
                        <el-tag type="info" v-if="scope.row.status == 0">禁用</el-tag>
                        <el-tag type="primary" v-if="scope.row.status == 1">正常</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="190" />
                <el-table-column prop="remark" label="备注信息" />
                <el-table-column label="操作" min-width="150" align="center">
                    <template #default="scope">
                        <span style="padding: 0 20px;" class="l" @click="openDialog(scope.row.channelId)"><el-icon>
                                <Edit />
                            </el-icon>修改</span>
                        <span class="r" @click="handleDelete(scope.row.channelId)"><el-icon>
                                <Delete />
                            </el-icon>删除</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <Pagination :total="total" @changePage="setPage" @changeRows="setRows"></Pagination>
        <el-dialog v-model="dialogVisible" :title="id ? '编辑渠道' : '添加渠道'" width="500">
            <el-form ref="channelFormRef" :model="channelForm" :rules="rules" label-width="auto" class="demo-ruleForm"
                :size="formSize" status-icon>
                <el-form-item label="渠道名称" prop="channelName">
                    <el-input v-model="channelForm.channelName" placeholder="请输入渠道名称" />
                </el-form-item>
                <el-form-item label="渠道状态" prop="status">
                    <el-radio-group v-model="channelForm.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="渠道类型" prop="type">
                    <el-radio-group v-model="channelForm.type">
                        <el-radio :label="1">线上渠道</el-radio>
                        <el-radio :label="2">线下渠道</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注信息" prop="remark">
                    <el-input v-model="channelForm.remark" :rows="2" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>
                <div class="dialog-footer" style="display: flex;justify-content: end;">
                    <el-button v-if="id" type="primary" @click="editActivityForm(channelFormRef)">编辑</el-button>
                    <el-button v-else type="success" @click="addActivityForm(channelFormRef)">添加</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </div>


            </el-form>
        </el-dialog>
        <!-- 上传文件 -->
        <el-dialog v-model="dialogVisible1" title="用户导入" width="500" >
            <input type="file" @change="handleFileChange" accept=".xlsx, .xls"  class="inpuFill"/>
            <el-upload class="upload-demo" drag action="http://47.104.167.34:9100/prod-api/tienchin/channel/importData"
                multiple>
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处,或<em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        <div>
                            <h4>是否更新已经存在的渠道数据</h4>
                            <p>仅允许导入xls,xlsx格式文件.<em>下载模板</em></p>
                        </div>
                    </div>
                </template>
            </el-upload>
            
            <el-button type="success" @click="PUTdialogOpen">确定</el-button>
                <el-button @click="dialogVisible1 = false">取消</el-button>
        </el-dialog>
        <!-- 导入的文件形式 -->
        <el-dialog v-model="PUTdialog" title="导入文件浏览" width="800">
                <el-table :data="DaoRuList">
                <el-table-column property="索引编码" label="索引编码"  />
                <el-table-column property="客户名称" label="客户名称" />
                <el-table-column property="手机号码" label="手机号码" />
                <el-table-column property="渠道来源" label="渠道来源" />
                <el-table-column property="创建时间" label="创建时间" width="200" />
                </el-table>
            </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {
    Refresh,
    Search,
} from '@element-plus/icons-vue'
import { onMounted, reactive, ref, toRaw, watch } from 'vue';
import { ChannelListget, addChannel, ChannelData, editChannel, ChannelDelete, findChannel, expostChannel } from "../../../api/index"
import { ComponentSize, ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import Pagination from '../Pagination.vue';
//查询页数
const newWorld = ref({
    pageNum: 1,
    pageSize: 10,
})
const showHeader = ref(true);
// 分页器返回参数 通过自定义事件
const setPage = (n: number) => {
    newWorld.value.pageNum = n;
    getChannelList();
};
const setRows = (n: number) => {
    newWorld.value.pageSize = n;
    getChannelList();
};
import * as XLSX from 'xlsx';
//--------------------------------------------------------------------下载文件
const exportToExcel = () => {
    // 创建一个工作簿
    const workbook = XLSX.utils.book_new();

    // 创建一个工作表
    const data = channel.value.map(item => [
        item.name,
        item.nextTime,
        item.status === 0 ? "未分配" : "已分配",
        item.owner,
        item.createTime
    ]);
    const worksheet = XLSX.utils.aoa_to_sheet(data);

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

    // 生成Excel文件
    XLSX.writeFile(workbook, 'data.xlsx');
};
//----------------------------------------------------------------------导入文件-----------------------------------------------------------------------
const PUTdialog = ref(false);
const PUTdialogOpen = () => {
    PUTdialog.value = true;
    dialogVisible1.value = false;
};
let data:any = ref([]);
let headers:any = ref([]);
const DaoRuList = ref([]);//渲染导入的数据
const handleFileChange = (event: any) => {
    const file = event.target.files[0];
    if (file) {
        readFile(file);
    }
};
const readFile = (file: any) => {
    const reader = new FileReader();
        reader.onload = (e) => {
          let dataA:any = new Uint8Array(e.target.result);
          const workbook = XLSX.read(dataA, { type: 'array' });
          const sheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[sheetName];
          const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
  
            headers = json[0];
            data = json.slice(1);
            let Arrs:any = [];
            DaoRuList.value = Arrs;
            // console.log("超级最终数据",DaoRuList.value);
            data.forEach((item:any) => {
            const obj = {};
            headers.forEach((header:any, index:any) => {
              obj[header] = item[index];
            });
            Arrs.push(obj);
          });
        //   console.log(Arrs);//最终获取到的数据
          
        };
        reader.readAsArrayBuffer(file);

        
}




const formSize = ref<ComponentSize>("default");
const channelFormRef = ref<FormInstance>();
const channelForm = reactive({
    channelId: 0,
    channelName: "",
    type: 1,
    status: 1,
    remark: ""
});
const id = ref(0);

import { formdata } from "../../../utils/format"
import { status } from 'nprogress';

// watch(() => channelForm.fundTimeArray, (newVal) => {
//     console.log(newVal)
//     const formatTimeArray = ref([])
//     newVal.forEach(el => {
//         // console.log(el)
//         formatTimeArray.value.push(formdata.formDate(el))
//         channelForm.beginTime = formatTimeArray.value[0]
//         channelForm.endTime = formatTimeArray.value[1]
//     });
// })
const rules = reactive<FormRules>({
    channelName: [{ required: true, message: "请输入渠道名称", trigger: "blur" }],
    status: [
        {
            required: true,
            message: "请选择渠道状态",
            trigger: "change",
        },
    ],
    type: [
        {
            required: true,
            message: "请选择渠道类型",
            trigger: "change",
        },
    ],
});
const channelId = ref('')
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const value = ref('')
const value1 = ref('')
const value2 = ref('')
const options1 = [
    {
        value: '1',
        label: '正常',
    },
    {
        value: '0',
        label: '禁用',
    }
]
const options2 = [
    {
        value: '2',
        label: '线下渠道',
    },
    {
        value: '1',
        label: '线上渠道',
    }
]
const queryInfo = ref({//---------------搜索查询上传
    channelName: "",
    pageNum: 1,
    pageSize: 10,
    status: "",
    type: "",
    createTime: ""
});
const channel = ref([]);//---------------*******页面的数据*****-----------------------
const selectedActivities = ref([])//---------多选获取到的数据------------
const openDialog1 = () => {
    dialogVisible1.value = true
}
const openNewDialog = () => {
    id.value = getSubstringBeforeComma(getSelectedChannelIds());
    console.log(id.value)
    ChannelData(id.value).then(res => {
        Object.entries(res.data.data).map((item) => {
            channelForm[item[0]] = item[1];
        })
    })
    dialogVisible.value = true
    channelForm.channelId = id.value
}
const openDialog = (data: any) => {
    id.value = data;
    ChannelData(data).then(res => {
        Object.entries(res.data.data).map((item) => {
            channelForm[item[0]] = item[1];
        })
    })
    dialogVisible.value = true
    channelForm.channelId = data
}
const resetForm = () => {
    queryInfo.value.channelName = ""
    queryInfo.value.status = ''
    queryInfo.value.createTime = ''
    queryInfo.value.type = ''
};
const openUserDialog = () => {
    id.value = 0;
    dialogVisible.value = true
    channelForm.channelId = 0
    channelForm.channelName = ""
    channelForm.status = 0
    channelForm.type = 0
    channelForm.remark = ""
}
const addActivityForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            addChannel(channelForm).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("添加渠道失败");
                ElMessage.success("添加渠道成功");
                getChannelList();
                dialogVisible.value = false
            });
        } else {
            console.log("error submit!", fields);
        }
    });
};
const deleteActivityAll = () => {
    const ids = getSelectedChannelIds()
    ElMessageBox.confirm("是否确认删除渠道编号为" + ids + "的数据项?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            ChannelDelete(ids).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("删除渠道失败");
                ElMessage.success("删除渠道成功");
                getChannelList();
            });
        })
        .catch(() => {
            ElMessage.info("取消删除");
        });

};
const channelExport = () => {
    expostChannel().then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("导出渠道失败");
        ElMessage.success("导出渠道成功");
    });
}
const handleDelete = (data: any) => {
    ElMessageBox.confirm("是否确认删除渠道编号为" + data + "的数据项?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            ChannelDelete(data).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("删除渠道失败");
                ElMessage.success("删除渠道成功");
                getChannelList();
            });
        })
        .catch(() => {
            ElMessage.info("取消删除");
        });
}
const editActivityForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            channelForm.createTime = ""
            channelForm.updateTime = ""
            editChannel(channelForm).then((res: any) => {
                if (res.data.code != 200) return ElMessage.error("修改渠道失败");
                ElMessage.success("修改渠道成功");
                getChannelList();
                dialogVisible.value = false
            });
        } else {
            console.log("error submit!", fields);
        }
    });
};
const findActivityList = () => {
    findChannel(queryInfo).then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("查询渠道失败");
        channel.value = res.data.rows;
    });
}
const total = ref(0)
const getChannelList = () => {//-----------------------------------------------------------------------渲染页面数据
    findChannel(newWorld.value).then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("查询渠道失败");
        channel.value = res.data.rows.reverse();
        total.value = res.data.total;
    });
}
const findChannelList = () => {
    findChannel(queryInfo.value).then((res: any) => {
        if (res.data.code != 200) return ElMessage.error("查询渠道失败");
        channel.value = res.data.rows;
    });
}
const handleSelectionChange = (selection) => {
    selectedActivities.value = selection;
}
const putIs = ref(false);//修改的开关
const deleIs = ref(false);//删除的开关
const getSelectedChannelIds = () => {
    // console.log('选中的数据',selectedActivities.value.length);
    if (selectedActivities.value.length == 1) {
        putIs.value = true
        deleIs.value = true
    }else {
        putIs.value = false
    }

    const channelIds = selectedActivities.value.map(item => item.channelId);
    return channelIds.join(',');
}
const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确定要关闭吗?')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}
function getSubstringBeforeComma(str) {//---------------------封装的截取字符串的方法
    const index = str.indexOf(',');
    if (index === -1) {
        return str;
    }
    return str.substring(0, index);
}
onMounted(() => {
    getChannelList();
})
</script>

<style scoped lang="scss">
.channel {
    width: 100%;
    height: 100%;
    padding: 20px;

    .header {

        i {
            margin-right: 10px;
        }
    }

    .nav {
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        i {
            margin-right: 10px;
        }
    }

    .toBe {
        margin-bottom: 20px;

        .l,
        .r {
            color: #409dfe;
            cursor: pointer;
            display: inline-block;

            i {
                padding-top: 4px;
            }
        }

        .r {
            margin-left: 10px;
        }
    }
}

.el-upload__tip {
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;

    div {
        text-align: center;
    }

    em {
        color: #409dfe;
    }
}
::v-deep .el-dialog__body{
    position: relative !important;
}
.inpuFill{
    position: absolute;
    top: 25px;
    left: 0;
    width: 500px;
    height: 200px;
    z-index: 999;
    border-radius: 4px;
    opacity: 0;
}
</style>